package com.hrzyit.whistle.cases.ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bigkoo.alertview.AlertView
import com.bigkoo.alertview.OnItemClickListener
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.hrzyit.base.common.BaseConstant
import com.hrzyit.base.ext.dip2px
import com.hrzyit.base.ext.startLoading
import com.hrzyit.base.ui.adapter.BaseGridSpacingItemDecoration
import com.hrzyit.base.ui.adapter.BaseRecyclerViewAdapter
import com.hrzyit.base.ui.fragment.BaseMvpFragment
import com.hrzyit.base.utils.AppPrefsUtils
import com.hrzyit.base.utils.DateUtils
import com.hrzyit.base.widgets.CaseButton
import com.hrzyit.provider.common.ProviderConstant
import com.hrzyit.provider.enums.UserRoleEnum
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.common.CaseConstant
import com.hrzyit.whistle.cases.data.bean.*
import com.hrzyit.whistle.cases.injection.component.DaggerCaseInfoComponent
import com.hrzyit.whistle.cases.injection.module.CaseCenterModule
import com.hrzyit.whistle.cases.injection.module.UploadModule
import com.hrzyit.whistle.cases.presenter.CaseInfoPresenter
import com.hrzyit.whistle.cases.presenter.view.CaseInfoView
import com.hrzyit.whistle.cases.ui.activity.*
import com.hrzyit.whistle.cases.ui.adapter.CaseButtonAdapter
import com.hrzyit.whistle.cases.ui.adapter.ImageUploadViewAdapter
import com.hrzyit.whistle.cases.widgets.CaseAcceptPopup
import com.hrzyit.whistle.cases.widgets.CaseApplyClosePopup
import com.hrzyit.whistle.cases.widgets.CaseWhistleConfirmPopup
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.app.TakePhotoImpl
import com.jph.takephoto.compress.CompressConfig
import com.jph.takephoto.model.TResult
import com.kennyc.view.MultiStateView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.XPopupImageLoader
import kotlinx.android.synthetic.main.fragment_case_info.*
import org.jetbrains.anko.support.v4.intentFor
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.toast
import java.io.File
import java.util.*

/**
 * 案件详情界面
 * @author YangWei
 * @date 2019/4/8
 */
class CaseInfoFragment : BaseMvpFragment<CaseInfoPresenter>(),
    CaseInfoView, TakePhoto.TakeResultListener {

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mTakePhoto.onActivityResult(requestCode, resultCode, data)
    }

    companion object {
        const val TAG = "CaseInfoFragment"
    }

    private lateinit var activity: Activity

    private lateinit var buttonList: MutableList<CaseButton>

    // 上报问题图片集合
    private lateinit var reportUploadFileList: MutableList<UploadInfo>

    // 上报问题描述音频文件
    private lateinit var reportUploadAudioFile: UploadInfo

    // 处置图片集合
    private var disposeUploadFileList: MutableList<UploadInfo> = mutableListOf()

    // 案件基本信息
    private lateinit var caseInfoEntity: CaseInfoEntity
    // 案件详细信息
    private lateinit var caseDetailInfoEntity: CaseDetailInfoEntity

    // 案件签收(受理/不受理)操作请求 Vo
    private lateinit var caseSignInVo: CaseSignInVo
    // 案件结案申请 vo
    private lateinit var caseApplyCloseVo: CaseApplyCloseVo

    // 组件：拍照 TakePhoto
    private lateinit var mTakePhoto: TakePhoto
    private lateinit var mTempFile: File

    // 按钮权限适配器
    private lateinit var caseButtonAdapter: CaseButtonAdapter

    // 案件上报图片适配器
    private lateinit var imageUploadReportAdapter: ImageUploadViewAdapter

    // 案件处置图片适配器
    private lateinit var imageUploadDisposeAdapter: ImageUploadViewAdapter

    private lateinit var caseAcceptPopup: CaseAcceptPopup
    private lateinit var caseApplyClosePopup: CaseApplyClosePopup

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = context as Activity
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_case_info, container, false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 初始化拍照组件
        mTakePhoto = TakePhotoImpl(this, this)
        mTakePhoto.onCreate(savedInstanceState)

//        EventBus.getDefault().register(this)

        initView()

//        loadData()
    }

    /**
     * 加载数据
     */
    private fun loadData() {
        mMultiStateView.startLoading()
        mMultiStateView.viewState = MultiStateView.VIEW_STATE_CONTENT

        val id = activity.intent.getLongExtra("id", 0)

        mPresenter.getCaseInfoById(id)

        disposeUploadFileList = mutableListOf()


    }

    /**
     * 加载数据,Activity -> Fragment 跳转时刷新
     */
    override fun onResume() {
        super.onResume()
        loadData()
    }

    /**
     * 根据案件状态和角色显示按钮
     */
    private fun buildButtonList() {

        buttonList = mutableListOf()

        imageUploadDisposeAdapter.isDelete = false

        // 显示处置信息: 当前案件已指定处置人,且只有处置人可以修改处置信息
        val completeDept = caseInfoEntity.completeDeptId
        val completeUser = caseInfoEntity.completeUserId
        val completeTime = caseInfoEntity.completeTime
        when (completeDept != null && completeUser != null) {
            true -> {
                mCompleteContentLayout.visibility = View.VISIBLE
                mCompleteUploadLayout.visibility = View.VISIBLE
            }
        }
        // 案件状态: t_case_info.state
        val caseState = caseInfoEntity.status
        // 案件状态表：t_case_state
        val caseInfoState = caseInfoEntity.caseInfoState!!
        // 显示/隐藏受理按钮:指挥中心到单位,接收单位是否已受理 t_case_info.is_handler = 1
        val isHandle = caseInfoState.isHandler
        // 获取当前案件分类：批转类型需要是否已响应
        val caseSort = caseInfoEntity.caseSort
        // 当前登录人单位id
        val deptId = AppPrefsUtils.getLong(ProviderConstant.KEY_SP_USER_DEPT_ID)
        // 当前登录人角色id
        val roleId = AppPrefsUtils.getLong(ProviderConstant.KEY_SP_USER_ROLE_ID)
//        val currentUserRole = RoleUtils.getUserRole(roleId)
        when (roleId) {
            UserRoleEnum.FOURTH_HANDLER.ordinal.toLong() -> {
                when (completeDept != null && completeUser != null && completeTime == null) {
                    true -> {
                        // 处置员(第四方)
                        buttonList.add(
                            CaseButton(
                                R.id.caseSubmitProcessedBtnId, resources.getString(R.string.case_btn_submit_text)
                            )
                        )
                        // 设置文本编辑器可读写,默认只读
                        mCaseDisposeDescEt.isFocusable = true
                        mCaseDisposeDescEt.isFocusableInTouchMode = true
                        mCaseDisposeDescEt.isCursorVisible = true
                        // 设置处置图片可以上传,默认只读
                        // 初始化案件图片上传组件的上传按钮
                        disposeUploadFileList.add(
                            0,
                            UploadInfo(
                                null, null,
                                BaseConstant.DEFAULT_UPLOAD_SERVER, null,
                                null, null, null, 0, null
                            )
                        )
                        imageUploadDisposeAdapter.isDelete = true
                    }
                }
            }
            15L -> {
                // 外勤员(第三方) ？
                // 只显示案件信息
            }
//            21L, 22L -> {
//
//
//                // 查看进度
//                buttonList.add(
//                    CaseButton(
//                        R.id.caseProcessBtnId, resources.getString(R.string.case_btn_process_text)
//                    )
//                )
//
//                when (isHandle == 0) {
//                    true -> {
//                        // 未受理(指挥中心到单位)、未响应(单位到单位)
//                        when (caseState == 1) {
//                            true -> {
//                                buttonList.add(
//                                    CaseButton(
//                                        R.id.caseAcceptBtnId, resources.getString(R.string.case_btn_accept_text)
//                                    )
//                                )
//                                buttonList.add(
//                                    CaseButton(
//                                        R.id.caseRejectBtnId, resources.getString(R.string.case_btn_reject_text)
//                                    )
//                                )
//                            }
//                            false -> {
//                                when (caseSort == 3 && caseInfoState.handlerDept == deptId) {
//                                    true -> {
//                                        // 批转未响应
//                                        // 响应按钮
//                                        buttonList.add(
//                                            CaseButton(
//                                                R.id.caseReplyBtnId, resources.getString(R.string.case_btn_reply_text)
//                                            )
//                                        )
//                                        // 不响应按钮
//                                        buttonList.add(
//                                            CaseButton(
//                                                R.id.caseNotReplyBtnId,
//                                                resources.getString(R.string.case_btn_not_reply_text)
//                                            )
//                                        )
//                                    }
//                                }
//                            }
//                        }
//
//                    }
//                    else -> {
//                        // 派遣
//                        when (completeDept != null && completeUser != null) {
//                            false -> {
//                                buttonList.add(
//                                    CaseButton(
//                                        R.id.caseDispatchBtnId, resources.getString(R.string.case_btn_dispatch_text)
//                                    )
//                                )
//                            }
//                        }
//
//                        // 申请结案
//                        when (completeDept != null && completeUser != null && completeTime != null && caseState == 10) {
//                            true -> {
//                                buttonList.add(
//                                    CaseButton(
//                                        R.id.caseApplyCloseBtnId, resources.getString(R.string.case_btn_close_text)
//                                    )
//                                )
//                            }
//                        }
//                        // 申请延期
//                        when (completeTime == null && (caseState != 10 && caseState != 5 && caseState != 2)) {
//                            true -> {// 申请延期
//                                buttonList.add(
//                                    CaseButton(
//                                        R.id.caseApplyDelayBtnId, resources.getString(R.string.case_btn_delay_text)
//                                    )
//                                )
//                            }
//                        }
//                    }
//                }
//            }
            19L, 20L, 21L, 22L -> {
                // 社区、分管单位领导和办事员角色可操作功能
                // 查看进度
                buttonList.add(
                    CaseButton(
                        R.id.caseProcessBtnId, resources.getString(R.string.case_btn_process_text)
                    )
                )
                when (isHandle == 0) {
                    true -> {
                        // 未受理(指挥中心到单位)、未响应(单位到单位)
                        when (caseState == 1) {
                            true -> {
                                buttonList.add(
                                    CaseButton(
                                        R.id.caseAcceptBtnId, resources.getString(R.string.case_btn_accept_text)
                                    )
                                )
                                buttonList.add(
                                    CaseButton(
                                        R.id.caseRejectBtnId, resources.getString(R.string.case_btn_reject_text)
                                    )
                                )
                            }
                            false -> {
                                when (caseSort == 3 && caseInfoState.handlerDept == deptId) {
                                    true -> {
                                        // 批转未响应
                                        // 响应按钮
                                        buttonList.add(
                                            CaseButton(
                                                R.id.caseReplyBtnId, resources.getString(R.string.case_btn_reply_text)
                                            )
                                        )
                                        // 不响应按钮
                                        buttonList.add(
                                            CaseButton(
                                                R.id.caseNotReplyBtnId,
                                                resources.getString(R.string.case_btn_not_reply_text)
                                            )
                                        )
                                    }
                                }
                            }
                        }

                    }
                    else -> {
                        when (completeDept != null && completeUser != null) {
                            false -> {
                                // 派遣处置员
                                buttonList.add(
                                    CaseButton(
                                        R.id.caseDispatchBtnId, resources.getString(R.string.case_btn_dispatch_text)
                                    )
                                )
                                when (roleId) {
                                    // 社区、分管单位领导可以批转和吹哨
                                    19L, 20L -> {
                                        // 批转到其它单位
                                        buttonList.add(
                                            CaseButton(
                                                R.id.caseTransferBtnId,
                                                resources.getString(R.string.case_btn_transfer_text)
                                            )
                                        )
                                        // 吹哨
                                        buttonList.add(
                                            CaseButton(
                                                R.id.caseWhistleBtnId,
                                                resources.getString(R.string.case_btn_whistle_text)
                                            )
                                        )
                                    }
                                }
                            }
                        }

                        // 申请结案
                        when (completeDept != null && completeUser != null && completeTime != null && caseState == 10) {
                            true -> {
                                buttonList.add(
                                    CaseButton(
                                        R.id.caseApplyCloseBtnId, resources.getString(R.string.case_btn_close_text)
                                    )
                                )
                            }
                        }
                        // 申请延期
                        when (completeTime == null && (caseState != 10 && caseState != 5 && caseState != 2)) {
                            true -> {
                                buttonList.add(
                                    CaseButton(
                                        R.id.caseApplyDelayBtnId, resources.getString(R.string.case_btn_delay_text)
                                    )
                                )
                            }
                        }
                    }
                }


            }
            18L -> {
                // 街道领导

                // 查看进度
                buttonList.add(
                    CaseButton(
                        R.id.caseProcessBtnId, resources.getString(R.string.case_btn_process_text)
                    )
                )
                // 没有申请结案前都可以吹哨
                when(caseState != 5 && caseState != 2 && caseState!! > 1) {
                    true -> {
                        // 吹哨
                        buttonList.add(
                            CaseButton(
                                R.id.caseWhistleBtnId, resources.getString(R.string.case_btn_whistle_text)
                            )
                        )
                    }
                }
            }

        }
        // 设置权限按钮
        caseButtonAdapter.setData(buttonList)

        mCaseDisposeImagesRv.adapter = imageUploadDisposeAdapter

        // 案件处置图片组件适配器初始化数据
        imageUploadDisposeAdapter.setData(disposeUploadFileList)

        // 配置适配器中组件的事件
        imageUploadDisposeAdapter.setOnItemClickListener(object :
            BaseRecyclerViewAdapter.OnItemClickListener<UploadInfo> {
            override fun onItemClick(view: View, item: UploadInfo?, position: Int) {
                when (position + 1 == disposeUploadFileList.size && item!!.imageUrl.isNullOrEmpty()) {
                    true -> {
                        // 弹出添加上传图片组件
                        if (uploadPermission()) {
                            showCaseAddImageAlertView()
                        }
                    }
                    false -> {
                        // 已上传的图片点击显示全图
                        showPhotoScreenView(view.findViewById(R.id.mCaseImageIv), item!!.imageUrl)
                    }
                }

            }

        })

    }

    /**
     * 是否可以上传图片
     */
    private fun uploadPermission(): Boolean {
        return AppPrefsUtils.getLong(ProviderConstant.KEY_SP_USER_ROLE_ID) == 16L
    }

    /**
     * 显示图片全图
     */
    private fun showPhotoScreenView(imageView: ImageView, imageUrl: String) {
        XPopup.Builder(context)
            .asImageViewer(imageView, imageUrl, ImageLoader(context!!))
            .isShowSaveButton(false)
            .show()
    }

    /**
     * XPopupImageLoader 实现类
     */
    class ImageLoader(private val mContext: Context) : XPopupImageLoader {
        override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
            Glide.with(mContext).load(uri as String).into(imageView)
        }

        override fun getImageFile(context: Context, uri: Any): File {
            return Glide.with(context).load(uri).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get()
        }
    }

    /**
     * 初始化视图
     */
    private fun initView() {

        // 初始化案件处置组件数据源和布局
        val disposeLayoutManager = GridLayoutManager(activity, 4)
        imageUploadDisposeAdapter = ImageUploadViewAdapter(activity)

        // 初始化处置图片上传组件

        mCaseDisposeImagesRv.layoutManager = disposeLayoutManager


        // 初始化已上传的案件图片
        val reportLayoutManager = GridLayoutManager(activity, 4)
        mCaseReportImagesRv.layoutManager = reportLayoutManager

        imageUploadReportAdapter = ImageUploadViewAdapter(activity)
        imageUploadReportAdapter.isDelete = false

        mCaseReportImagesRv.adapter = imageUploadReportAdapter
        imageUploadReportAdapter.setOnItemClickListener(object :
            BaseRecyclerViewAdapter.OnItemClickListener<UploadInfo> {
            override fun onItemClick(view: View, item: UploadInfo?, position: Int) {
                showPhotoScreenView(view.findViewById(R.id.mCaseImageIv), item!!.imageUrl)
            }
        })


        // 根据案件状态显示按钮
        val buttonLayoutManager = GridLayoutManager(activity, 4)
        mCaseBtnRv.layoutManager = buttonLayoutManager
        mCaseBtnRv.addItemDecoration(
            BaseGridSpacingItemDecoration(
                4, this.dip2px(10.0f), this.dip2px(10.0f), false
            )
        )

        mCaseBtnRv.setHasFixedSize(true)

        caseButtonAdapter = CaseButtonAdapter(activity)
        mCaseBtnRv.adapter = caseButtonAdapter

        caseButtonAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<CaseButton> {
            override fun onItemClick(view: View, item: CaseButton?, position: Int) {
                when (item?.id) {
                    R.id.caseProcessBtnId -> {
                        // 查看进度按钮
                        startActivity<CaseTimeLineActivity>(
                            "caseId" to caseInfoEntity.id
                        )
                    }
                    R.id.caseAcceptBtnId -> {
                        // 受理案件按钮 Center To Dept
                        val userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)
                        caseSignInVo = CaseSignInVo(
                            userId,
                            caseInfoEntity.id,
                            1
                        )
                        mPresenter.signInCaseFromCenter(caseSignInVo)
                    }
                    R.id.caseRejectBtnId -> {
                        // 不受理案件按钮 Center To Dept
                        val userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)
                        caseSignInVo = CaseSignInVo(
                            userId,
                            caseInfoEntity.id,
                            0
                        )

                        caseAcceptPopup = CaseAcceptPopup(context!!, mPresenter)
                        caseAcceptPopup.caseSignInVo = caseSignInVo

                        XPopup.Builder(context)
                            .asCustom(caseAcceptPopup)
                            .show()
                    }
                    R.id.caseTransferBtnId -> {
                        // 批转按钮  Dept To Dept
                        when (caseInfoEntity.isWhistle) {
                            1 -> {
                                XPopup.Builder(context)
                                    .asConfirm("提示", "吹哨案件不能执行批转", null).show()
                            }
                            else -> {
                                startActivity(
                                    intentFor<SelectDeptAndUserActivity>(
                                        "tag" to CaseConstant.TAG_FRAGMENT_DEPT_INDEX_FOR_TRANSFER,
                                        "caseId" to caseInfoEntity.id
                                    )
                                )
                            }
                        }
                    }
                    R.id.caseReplyBtnId -> {
                        // 响应批转案件按钮 Dept To Dept
                        val userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)
                        caseSignInVo = CaseSignInVo(
                            userId,
                            caseInfoEntity.id,
                            1
                        )
                        mPresenter.signInCaseFromDept(caseSignInVo)
                    }
                    R.id.caseNotReplyBtnId -> {
                        // 不响应批转案件按钮 Dept to Dept
                        val userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)
                        caseSignInVo = CaseSignInVo(
                            userId,
                            caseInfoEntity.id,
                            0
                        )
                        mPresenter.signInCaseFromDept(caseSignInVo)
                    }
                    R.id.caseDispatchBtnId -> {
                        // 派遣处置人
                        // 弹出选择派遣人窗口
                        startActivity<SelectDeptUserActivity>("caseId" to caseInfoEntity.id)
                    }
                    R.id.caseApplyCloseBtnId -> {
                        // 申请结案按钮
                        val completeTime = caseInfoEntity.completeTime
                        when (completeTime != null) {
                            true -> {
                                val userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)
                                val deptId = AppPrefsUtils.getLong(ProviderConstant.KEY_SP_USER_DEPT_ID)
                                caseApplyCloseVo = CaseApplyCloseVo(
                                    caseInfoEntity.id,
                                    userId,
                                    deptId
                                )

                                caseApplyClosePopup = CaseApplyClosePopup(context!!, mPresenter)
                                caseApplyClosePopup.caseApplyCloseVo = caseApplyCloseVo

                                XPopup.Builder(context)
                                    .asCustom(caseApplyClosePopup)
                                    .show()
                            }
                            else -> {
                                XPopup.Builder(context)
                                    .asConfirm("提示", "当前案件未处置完成", null).show()
                            }
                        }

                    }
                    R.id.caseApplyDelayBtnId -> {
                        // 申请延期按钮
                        when (caseInfoEntity.isWhistle) {
                            1 -> {
                                XPopup.Builder(context)
                                    .asConfirm("提示", "吹哨案件不能执行申请延期", null).show()
                            }
                            else -> {
                                // TODO 2019/4/28 - 待完成内容：
                                XPopup.Builder(context)
                                    .asConfirm("提示", "功能正在开发", null).show()
                            }
                        }


                    }
                    R.id.caseWhistleBtnId -> {
                        // 吹哨按钮
//                        XPopup.Builder(context)
//                            .asConfirm("提示", "功能正在开发", null).show()
                        when (caseInfoEntity.isWhistle) {
                            1 -> {
                                // TODO 2019/5/14 - 待完成内容：跳转到群聊界面
                                XPopup.Builder(context)
                                    .asConfirm("提示", "吹哨案件不能执行批转", null).show()
                            }
                            else -> {
                                startActivity(
                                    intentFor<WhistleDeptAndUserActivity>(
                                        "tag" to CaseConstant.TAG_FRAGMENT_DEPT_INDEX_FOR_WHISTLE,
                                        "caseId" to caseInfoEntity.id
                                    )
                                )
                                // 弹出吹哨窗口, 添加单位和人员
//                                val whistleConfirmPopup = CaseWhistleConfirmPopup(activity, mPresenter)
//
//                                XPopup.Builder(activity)
//                                    .asCustom(whistleConfirmPopup)
//                                    .show()
                            }
                        }
                    }
                    R.id.caseSubmitProcessedBtnId -> {
                        // 提交保存处置信息
                        val userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)

                        val deptId = AppPrefsUtils.getLong(ProviderConstant.KEY_SP_USER_DEPT_ID)

                        val saveDisposeCaseInfoVo = SaveDisposeCaseInfoVo(
                            caseInfoEntity.id,
                            userId,
                            deptId
                        )
                        saveDisposeCaseInfoVo.description = "${mCaseDisposeDescEt.text}"

                        val list = mutableListOf<UploadInfo>()
                        disposeUploadFileList.forEach {
                            if (!it.originUrl.isNullOrBlank()) {
                                list.add(it)
                            }
                        }

                        saveDisposeCaseInfoVo.uploadFileList = list

                        mPresenter.saveCaseDisposeResult(saveDisposeCaseInfoVo)
                    }
                }
            }
        }) // end setOnItemClick

    }


    /**
     * Dagger2 注入
     */
    override fun injectComponent() {

        DaggerCaseInfoComponent.builder()
            .activityComponent(mActivityComponent)
            .caseCenterModule(CaseCenterModule())
            .uploadModule(UploadModule())
            .build()
            .inject(this)
        mPresenter.mView = this
    }

    /**
     * 获取案件详情信息回调
     */
    override fun onGetCaseInfoSuccess(result: CaseDetailInfoEntity) {

        this.caseInfoEntity = result.caseInfo
//        this.caseInfoEntity.caseInfoState = result.caseInfoState

        // 多状态视图-内容显示状态
        mMultiStateView.viewState = MultiStateView.VIEW_STATE_CONTENT

        // 案件任务单号
        mCaseTaskNumberCell.getRightView().text = caseInfoEntity.taskNumber

        // 案件问题类型
        mCaseQuestionCell.getRightView().text = caseInfoEntity.typeName

        // 案件大类名称
        mCaseOneSortCell.getRightView().text = caseInfoEntity.oneSortName

        // 案件小类名称
        mCaseSecondSortCell.getRightView().text = caseInfoEntity.secondSortName

        // 立案条件
        mCaseConditionCell.getRightView().text = caseInfoEntity.caseConditionName

        // 监督员
        // TODO 2019/4/21 - 待完成内容：第三方
        mCaseSupervisorCell.getRightView().text = "监督员"

        // 上报时间
        val times = caseInfoEntity.addTime!!

        mReportTimeCell.getRightView().text = DateUtils.format(Date(times.toLong()), "yyyy-MM-dd HH:mm:ss")

        // 案件地址
        mCaseAddressGPSCell.getRightView().text = caseInfoEntity.address

        // gps 信息

        // 案件描述文本
        mCaseReportDescEt.text = caseInfoEntity.description

        // 案件上报图片
        reportUploadFileList = result.uploadList

        reportUploadFileList.let {
            imageUploadReportAdapter.setData(it)
        }

        // 案件描述音频文件
//        reportUploadFileList = result.uploadAudioFileList

        // 案件处置描述

        mCaseDisposeDescEt.setText(result.disposeResult)

        // 案件处置图片
        disposeUploadFileList = result.disposeList
        disposeUploadFileList.let {
            if (it.size > 0) imageUploadDisposeAdapter.setData(it)
        }

        buildButtonList()
    }

    /**
     * 设置Back是否可见
     */
    fun setBackVisible(isVisible: Boolean) {
        mHeaderBar.getLeftView().visibility = if (isVisible) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }

    // 文件上传回调 --------------------------

    /**
     * 获取上传图片成功调用
     */
    override fun takeSuccess(result: TResult?) {
        // 获取成功
        val photo = result?.image?.compressPath
        // 上传图片到服务器
        photo?.let {
            mPresenter.uploadPhoto(it)
        }

    }

    /**
     * 取消选择图片调用
     */
    override fun takeCancel() {
        // 取消选择
        Log.d("取消选择", "cancel")
    }

    /**
     * 获取图片失败调用
     */
    override fun takeFail(result: TResult?, msg: String?) {
        // 获取失败
        Log.d("获取失败", msg)
    }

    /**
     * 弹出案件处置上传图片选择窗口
     */
    fun showCaseAddImageAlertView() {
        AlertView(
            "上传处置结果",
            null,
            "取消",
            null,
            arrayOf("拍照", "从相册中选择"),
            context,
            AlertView.Style.ActionSheet,
            OnItemClickListener { _, position ->
                ActivityCompat.requestPermissions(
                    activity,
                    arrayOf(
                        "android.permission.CAMERA",
                        "android.permission.WRITE_EXTERNAL_STORAGE"
                    ),
                    17
                )

                // 照片压缩，每次都要调用否则只会执行一次
                val config = CompressConfig.ofDefaultConfig()
                // 压缩比 300k
                config.maxSize = 300 * 1024
                mTakePhoto.onEnableCompress(config, false)
                when (position) {
                    0 -> {
                        // 创建照片临时文件
                        createTempFile()
                        // 拍照
                        mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
                    }
                    1 -> {
                        mTakePhoto.onPickFromGallery()
                    }
                }
            }
        ).show()
    }

    /**
     * 创建上传图片临时文件
     */
    private fun createTempFile() {
        val tempFileName = "${DateUtils.curTime}.png"
        when (Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageState() -> {
                // 在存储卡中创建
                this.mTempFile = File(Environment.getExternalStorageDirectory(), tempFileName)
            }
            else -> {
                // 在内存中创建
                this.mTempFile = File(activity.filesDir, tempFileName)
            }
        }
    }

// 回调方法 ----------------------------------------------


    override fun onSignInCaseFromDeptResult(result: Boolean) {
        // 响应/不响应操作结果
        when (result) {
            true -> {
                activity.finish()
                // 刷新案件详情页面
                startActivity<CaseInfoActivity>("id" to caseInfoEntity.id)
            }
        }
    }

    override fun onSignInCaseFromCenterResult(result: Boolean) {
        // 受理/不受理操作结果
        when (result) {
            true -> {
                if (::caseAcceptPopup.isInitialized) {
                    caseAcceptPopup.dismiss()
                }
//                // 受理完成后,显示派遣按钮
//                activity.findViewById<Button>(R.id.caseAcceptBtnId).visibility = View.GONE
//                activity.findViewById<Button>(R.id.caseRejectBtnId).visibility = View.GONE
//                activity.findViewById<Button>(R.id.caseWhistleBtnId).visibility = View.VISIBLE
//                activity.findViewById<Button>(R.id.caseTransferBtnId).visibility = View.VISIBLE
//                activity.findViewById<Button>(R.id.caseApplyDelayBtnId).visibility = View.VISIBLE
//                activity.findViewById<Button>(R.id.caseDispatchBtnId).visibility = View.VISIBLE
                activity.finish()
                // 刷新案件详情页面
                startActivity<CaseInfoActivity>("id" to caseInfoEntity.id)
            }
        }
    }

    /**
     * 案件处置图片上传回调，刷新处置图片显示区域
     */
    override fun onDisposeUploadResult(result: UploadInfo) {

        // 获取服务器返回的图片网络地址信息
//        val url = "${result.fileHost}${result.getGroup}/${result.getPath}"
//        result.addTime = DateUtils.getNow("yyyy/MM/dd HH:mm:ss")
        // 将上传的图片交给 GridViewAddImageAdapter 管理
        // Glide 是反向显示列表数据，所以要在 disposeUploadFileList 的下标0的位置插入新图片对象
        disposeUploadFileList.add(0, result)
        imageUploadDisposeAdapter.setData(disposeUploadFileList)
    }


    /**
     * 案件处置信息保存结果回调
     */
    override fun onGetSaveCaseDisposeResult(result: Boolean) {
        when (result) {
            true -> {
                toast("保存处置信息完成")
                // TODO 2019/4/28 - 待完成内容：保存完成后,返回上一页面
                activity.finish()
            }
            else -> {
                toast("保存处置信息有问题")
            }
        }
    }

    /**
     * 案件处置信息保存结果回调
     */
    override fun onGetApplyCaseCloseResult(result: Boolean) {
        when (result) {
            true -> {
                toast("申请结案完成")
                caseApplyClosePopup.dismiss()
                activity.finish()
            }
            else -> {
                toast("保存处置信息有问题")
            }
        }
    }


    /**
     * 处理选择派遣人事件
     */
//    @Subscribe(threadMode = ThreadMode.POSTING)
//    fun onSaveCaseDisposeUserEvent(event: SaveCaseDisposeUserEvent) {
//
//        val newButtonList = mutableListOf<CaseButton>()
//        buttonList.forEach {
//            when(it.id) {
//                R.id.caseDispatchBtnId -> {
//                }
//                else -> {
//                    newButtonList.add(it)
//                }
//            }
//        }
//        caseButtonAdapter.setData(newButtonList)
//    }
//
//    override fun onDestroy() {
//        EventBus.getDefault().unregister(this)
//        super.onDestroy()
//    }
}

